package com.sservice.service.service.impl;

import com.sservice.banfu.e.SalePerson;
import com.sservice.banfu.mapper.SalePersonMapper;
import com.sservice.banfu.service.SalePersonService1;
import com.sservice.banfu.vo.SalePersonVo;
import com.sservice.common.Constants;
import com.sservice.model.dao.*;
import com.sservice.model.entity.*;
import com.sservice.model.vo.SaleCommissionVo;
import com.sservice.model.wx.Template;
import com.sservice.model.wx.TemplateParam;
import com.sservice.service.common.AdvancedUtil;
import com.sservice.service.service.IOrderService;
import com.sservice.service.service.ISaleCommissionService;
import com.sservice.service.service.ISalePersonAccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class SaleCommissionImpl implements ISaleCommissionService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ISaleCommissionDao userDao;
    @Autowired
    private ISalePersonAccountDao spaDao;
    @Autowired
    private ISalePersonAccountService spaService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOfferDao offerDao;
    @Autowired
    private SalePersonMapper salePersonMapper;
    @Autowired
    private SalePersonService1 salePersonService1;
    @Autowired
    private UserWxMapper userWxDao;
    @Autowired
    private AdvancedUtil advancedUtil;

    @Override
    public List<SaleCommission> queryByPage(SaleCommissionVo user) {
        return userDao.queryByPage(user);
    }

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return userDao.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(SaleCommission record) {
        return userDao.insert(record);
    }

    @Override
    public int insertSelective(SaleCommission record) {
        return userDao.insertSelective(record);
    }

    @Override
    public int proofread() {
        SaleCommissionVo scv = new SaleCommissionVo();
        List<SaleCommission> scList = userDao.proofreadSelect(scv);
        for (int i = 0; i < scList.size(); i++) {
            SaleCommission sc = scList.get(i);
            Order order = orderService.selectByPrimaryKey(Integer.valueOf(sc.getOrderId())); // order
            Offer offer = offerDao.selectByPrimaryKey(Integer.valueOf(order.getOfferId()));// offer [price
            if (sc.getSaleId().equals(order.getSaleId())) {
                sc.setPercent(BigDecimal.valueOf(offer.getSalesMan()));
                // 执行中，终止执行，执行完毕
                if (order.getStatus().equals("0") || order.getStatus().equals("1") || order.getStatus().equals("3")) {
                    sc.setCommission(order.getNumber().multiply(sc.getPercent()));
                } else if (order.getStatus().equals("2")) { // 强制执行完毕
                    sc.setCommission(order.getActualNumber().multiply(sc.getPercent()));
                }
            } else {
                sc.setPercent(BigDecimal.valueOf(offer.getSalesManager()));//销售经理
                // 执行中，终止执行，执行完毕
                if (order.getStatus().equals("0") || order.getStatus().equals("1") || order.getStatus().equals("3")) {
                    sc.setCommission(order.getNumber().multiply(sc.getPercent()));

                } else if (order.getStatus().equals("2")) { // 强制执行完毕
                    sc.setCommission(order.getActualNumber().multiply(sc.getPercent()));
                }
            }

            if (order.getStatus().equals("2") || order.getStatus().equals("3")) {
                sc.setStatus("1");
            } else if (order.getStatus().equals("1")) {
                sc.setStatus("2");
            } else {
                sc.setStatus("0");
            }
            userDao.updateByPrimaryKeySelective(sc);
        }
        List<SalePersonAccount> list = spaDao.proofreadSelect();
        for (int i = 0; i < list.size(); i++) {
            SalePersonAccount apa = list.get(i);
            SaleCommission sc = new SaleCommission();
            sc.setSaleId(apa.getSaleId());
            List<SaleCommission> list_ = userDao.selectBy(sc);
//            for (int j = 0; j < list_.size(); j++) {
//                SaleCommission sc1 = list_.get(j);
//                apa.setCashTotal(apa.getCashTotal().add(sc1.getCommission()));
//                if (sc1.getStatus().equals("0")) {
//                    apa.setCashWillReceiveTotal(apa.getCashWillReceiveTotal().add(sc1.getCommission()));
//                }
//                if (sc1.getStatus().equals("1")) {
//                    apa.setCashCanWithDrawTotal(apa.getCashCanWithDrawTotal().add(sc1.getCommission()));
//                }
//            }
            spaDao.updateByPrimaryKeySelective(apa);
        }

        return 0;
    }

    @Override
    public SaleCommission selectByPrimaryKey(Integer id) {
        return userDao.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(SaleCommission record) {
        return userDao.updateByPrimaryKeySelective(record);
    }

    /**
     * 佣金发放
     *
     * @param record record.orderId 必填，record.saleId
     * @return
     */
    @Override
    public Object giveCommission(SaleCommission record) {
        //佣金返现
        SaleCommission sc_res = userDao.selectOneByOrderId(record);
        String status = sc_res.getStatus();
        if (sc_res != null) {
            Order order = orderService.selectByPrimaryKey(Integer.valueOf(sc_res.getOrderId()));
            if (!"1".equals(order.getStatus())) {
//                int res_commsiion =
                sendComission(sc_res);
            }
            // 入账模板消息通知
            List<TemplateParam> paras = new ArrayList<TemplateParam>();
            if ("1".equals(status)) { //
                paras.add(new TemplateParam("first", "由于某些客观原因造成前次数量有误，订单实际数量更正为" + order.getActualNumber() + "，因此本本订单你实际获得的佣金为" + sc_res.getCommission() + ",以此为准，给您造成不变敬请谅解", "#333333"));
            } else if ("1".equals(order.getStatus())) {
                paras.add(new TemplateParam("first", "您订单号为" + order.getNo() + "的订单已经被终止执行!", "#333333"));
            } else {
                paras.add(new TemplateParam("first", "您获得订单佣金提成" + Constants.format2Double(sc_res.getCommission().doubleValue()) + "元!", "#333333"));
            }

            paras.add(new TemplateParam("order", order.getNo(), "#333333"));
            paras.add(new TemplateParam("money", ("1".equals(order.getStatus()) ? "0.00" : Constants.format2Double(sc_res.getCommission().doubleValue())), "#333333"));
            paras.add(new TemplateParam("remark", "点击查看佣金账户及明细!", "#333333"));
            this.sendReturnedCommission(sc_res, paras);

            if (!"1".equals(order.getStatus())) {
                //模板消息通知
                record.setSaler(record.getSaleId());
                record.setSaleId(null);
                SaleCommission scManager = userDao.selectOneByOrderId(record);
                if (scManager != null) { //是某一销售经理销售员
                    int res_manager_commsiion = sendComission(scManager);
                    if (res_manager_commsiion > 0) {
                        // 入账模板消息通知
                        List<TemplateParam> paras_ = new ArrayList<TemplateParam>();
                        paras_.add(new TemplateParam("first", "您获得订单佣金提成" + Constants.format2Double(sc_res.getCommission().doubleValue()) + "元!", "#333333"));
                        paras_.add(new TemplateParam("order", order.getNo(), "#333333"));
                        paras_.add(new TemplateParam("money", Constants.format2Double(sc_res.getCommission().doubleValue()), "#333333"));
                        paras_.add(new TemplateParam("remark", "点击查看佣金账户及明细!", "#333333"));
                        this.sendReturnedCommission(scManager, paras_);
                    }
                }
            }
        }
        return null;
    }

    public int sendComission(SaleCommission sc_res) {
        if ("1".equals(sc_res.getStatus())) {
            SalePersonAccount spa_res = spaDao.selectBySaleID(sc_res.getSaleId());
            spa_res.setCashCanWithDrawTotal(spa_res.getCashCanWithDrawTotal().subtract(sc_res.getCommission()));
            spa_res.setCashTotal(spa_res.getCashTotal().subtract(sc_res.getCommission())); //累计
            spaDao.updateByPrimaryKeySelective(spa_res);
        }
        Order order = orderService.selectByPrimaryKey(Integer.valueOf(sc_res.getOrderId()));
        SalePersonAccount spa_res = spaDao.selectBySaleID(sc_res.getSaleId());
        if (!"1".equals(sc_res.getStatus())) {
            spa_res.setCashWillReceiveTotal(spa_res.getCashWillReceiveTotal().subtract(sc_res.getCommission()));
        }
        sc_res.setCommission(sc_res.getPercent().multiply(order.getActualNumber()));
        spa_res.setCashCanWithDrawTotal(spa_res.getCashCanWithDrawTotal().add(sc_res.getCommission()));
//        spa_res.setCashWillReceiveTotal(spa_res.getCashWillReceiveTotal().subtract(sc_res.getCommission()));// kou
        spa_res.setCashTotal(spa_res.getCashTotal().add(sc_res.getCommission())); //累计
        spaDao.updateByPrimaryKeySelective(spa_res);
        sc_res.setStatus("1"); //1入账
        return userDao.updateByPrimaryKeySelective(sc_res);

    }

    /***
     * 强制执行完成订单修正佣金金额
     * @param sc
     * @param actual
     */
    @Transactional
    @Override
    public void proofCommission(SaleCommission sc, BigDecimal actual) {
        SalePersonAccount spa = spaService.selectBySaleId(String.valueOf(sc.getSaleId())); // 获取销售员账户
        spa.setCashWillReceiveTotal(spa.getCashWillReceiveTotal().subtract(sc.getCommission()).add(actual));
        spaDao.updateByPrimaryKeySelective(spa); // 更新账户
        sc.setCommission(actual);
        userDao.updateByPrimaryKeySelective(sc); //更新佣金
    }

    /**
     * @param sc     sc.saleId
     * @param params 模板内容
     * @return
     */
    public Object sendReturnedCommission(SaleCommission sc, List<TemplateParam> params) {
        if (Constants.domain.indexOf("localhost") > -1) { // 调试环境，禁止发送
            return null;
        }
        SalePersonVo salepManager = salePersonService1.selectByPrimaryKey(Integer.valueOf(sc.getSaleId()));
        if (salepManager.getOpenid() != null) {
            UserWx uwManager = new UserWx();
            uwManager.setUnionid(salepManager.getOpenid());
            uwManager.setUnitid(Constants.WXUserTypeWX);
            UserWx ux1Manager = userWxDao.selectByUnionid(uwManager);
            if (ux1Manager != null && ux1Manager.getOpenid() != null) { //系统包含微信账户
                Template tem = new Template();
                tem.setTemplateId(Constants.tmplReturnedCommission);
                tem.setTopColor("#00DD00");
                tem.setToUser(ux1Manager.getOpenid());
                tem.setUrl(Constants.domain + "/wx/user/index.html");
//                List<TemplateParam> paras = new ArrayList<TemplateParam>();
//                TemplateParam tp = tem.g
//                paras.add(new TemplateParam("first", "您将获得销售员" + sp.getName() + "订单销售经理提成" + scManger.getCommission() + "元!", "#333333"));
//                paras.add(new TemplateParam("order", order.getNo(), "#333333"));
//                paras.add(new TemplateParam("money", String.valueOf(scManger.getCommission()), "#333333"));
//                paras.add(new TemplateParam("remark", "点击查看佣金账户及明细!", "#333333"));


                tem.setTemplateParamList(params);
                advancedUtil.senderTmplSms(tem);
            }
        }
        return null;
    }

    @Override
    public int queryCount(SaleCommissionVo user) {
        return userDao.queryCount(user);
    }
}
